const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	let staff = await db.collection('staff').field({
		group_id: true,
	}).where({
		_openid: wxContext.OPENID,
		shop_id: event.shop_id,
	}).get()
	if (staff.data.length == 0) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	staff = staff.data[0]

	if (staff.group_id != 1) {
		//仅创始人可操作员工管理
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	
	if (event.op == 'set'||event.op=='delete') {
		let count = await db.collection('staff').where({
			shop_id: event.shop_id,
			_id: event._id,
		}).count()
		if (count.total == 0) {
			return {
				code: 20007,
				msg: '员工不存在',
			}
		}
		if(event.op=='set'){
			let rules = {
				setting: '门店设置',
				product: '项目管理',
				appointsetting: '预约设置',
				appoints: '预约记录',
				codes: '校验规则',
			}
			let data = {
				update_time: new Date(),
			}
			for (let x in rules) {
				data['rule_' + x] = event['rule_' + x]
			}
			let res = await db.collection('staff').doc(event._id).update({
				data
			})
			if (res.errMsg == "document.update:ok"){
				return {
					code: 200,
					msg: '保存成功',
					data: event._id
				}
			}
		}else{
			let res = await db.collection('staff').where({
				shop_id: event.shop_id,
				_id: event._id,
			}).remove()
			return {
				code: 200,
				msg: '删除成功',
				data: res
			}
		}
		
	}else if(event.op=='changeGroup'){
		console.log(event)
		let staff = await db.collection('staff').where({
			shop_id: event.shop_id,
			_id: event._id,
		}).field({
			group_id:true
		}).get()
		if(staff.data.length==0){
			return {
				code: 20007,
				msg: '员工不存在',
			} 
		}
		staff = staff.data[0]
		if(event.val==staff.group_id){
			return {
				code: 200,
				msg: '操作成功',
			}
		}
		if((event.val==2&&staff.group_id==3)||(event.val==3&&staff.group_id==2)){
			await db.collection('staff').doc(event._id).update({
				data:{
					update_time:new Date(),
					group_id : event.val
				}
			})
		}else if(event.val==1){

		}
		return {
			code: 200,
			msg: '操作成功',
		}
	}
	return {
		code: 20005,
		msg: '保存失败',
	}

}